package org.example.FTP;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class FileServer {
    private static final int PORT = 8888;
    private static final String STORAGE_DIR = "D:\\logs\\server\\"; // 服务器存储文件的目录

    public static void main(String[] args) {
        // 创建存储目录
        new File(STORAGE_DIR).mkdirs();

        try (ServerSocket serverSocket = new ServerSocket(PORT)) {
            System.out.println("文件服务器已启动，端口：" + PORT);

            while (true) {
                // 等待客户端连接
                Socket clientSocket = serverSocket.accept();
                System.out.println("新客户端连接：" + clientSocket.getInetAddress());

                // 为每个客户端创建新线程处理
                new Thread(() -> handleClient(clientSocket)).start();
            }
        } catch (IOException e) {
            System.err.println("服务器错误：" + e.getMessage());
        }
    }

    private static void handleClient(Socket clientSocket) {
        try (
            DataInputStream dis = new DataInputStream(clientSocket.getInputStream());
            DataOutputStream dos = new DataOutputStream(clientSocket.getOutputStream())
        ) {
            // 读取客户端操作类型（UPLOAD/DOWNLOAD）
            String operation = dis.readUTF();
            
            if ("UPLOAD".equals(operation)) {
                receiveFile(dis, dos);
            } else if ("DOWNLOAD".equals(operation)) {
                sendFile(dis, dos);
            } else {
                dos.writeUTF("错误：不支持的操作");
            }

        } catch (IOException e) {
            System.err.println("客户端处理错误：" + e.getMessage());
        } finally {
            try {
                clientSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("客户端连接已关闭");
        }
    }

    // 接收客户端上传的文件
    private static void receiveFile(DataInputStream dis, DataOutputStream dos) throws IOException {
        // 读取文件名和大小
        String fileName = dis.readUTF();
        long fileSize = dis.readLong();
        System.out.println("准备接收文件：" + fileName + "，大小：" + fileSize + "字节");

        // 保存文件
        File file = new File(STORAGE_DIR + fileName);
        try (FileOutputStream fos = new FileOutputStream(file)) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            long totalRead = 0;

            // 读取文件内容
            while (totalRead < fileSize && (bytesRead = dis.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
                totalRead += bytesRead;
                // 简单的进度提示
                System.out.printf("接收进度：%.2f%%\r", (totalRead * 100.0) / fileSize);
            }
        }

        System.out.println("\n文件接收完成");
        dos.writeUTF("文件上传成功");
    }

    // 向客户端发送文件（下载）
    private static void sendFile(DataInputStream dis, DataOutputStream dos) throws IOException {
        // 读取客户端需要下载的文件名
        String fileName = dis.readUTF();
        File file = new File(STORAGE_DIR + fileName);

        if (!file.exists() || !file.isFile()) {
            dos.writeUTF("ERROR");
            dos.writeLong(0);
            return;
        }

        // 发送文件存在的标识、文件名和大小
        dos.writeUTF("OK");
        dos.writeUTF(fileName);
        dos.writeLong(file.length());
        System.out.println("准备发送文件：" + fileName + "，大小：" + file.length() + "字节");

        // 发送文件内容
        try (FileInputStream fis = new FileInputStream(file)) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            long totalSent = 0;

            while ((bytesRead = fis.read(buffer)) != -1) {
                dos.write(buffer, 0, bytesRead);
                totalSent += bytesRead;
                // 简单的进度提示
                System.out.printf("发送进度：%.2f%%\r", (totalSent * 100.0) / file.length());
            }
        }
        System.out.println("\n文件发送完成");
    }
}
